package com.handong.handserialprogram.module.routemap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.model.status.MissionOverResponse;
import com.handong.handserialprogram.module.base.BaseView;
import com.handong.handserialprogram.module.base.EmergencyActivity;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.JLog;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


public class RouteMapActivity extends EmergencyActivity<RouteMapPresenter> implements BaseView {

    private TextureMapView mMapView;
    private LinearLayout mTipLayout;
    private FrameLayout mPoliceLocate;
    private TextView mTipTextView;
    private AMap mAMap;
    private TextView mPositionDescribe;
    private UiSettings uiSettings;
    public List<LatLng> routeList;
    public List<LatLng> polygonList;
    public LatLng startMarkerPoint;
    public LatLng endMarkerPoint;
    public Polygon polygon;
    private boolean mIsAddStaEnd=false;
    private boolean mIsMapLoadFinish=false;


    @Override
    protected int getContentViewID() {
        return R.layout.activity_route_map;
    }

    @Override
    protected RouteMapPresenter createPresenter() {
        return new RouteMapPresenter(this);
    }

    @Override
    protected void initViewByID() {
        mTipLayout = (LinearLayout) findViewById(R.id.routeMapTipLayout);
        mPoliceLocate = (FrameLayout) findViewById(R.id.routeMapPoliceLocate);
        mTipTextView = (TextView) findViewById(R.id.receiveLocateTip);
        mPositionDescribe = (TextView) findViewById(R.id.mapLocateDescribe);
        mMapView = (TextureMapView) findViewById(R.id.catchCriminalMap);

        mPoliceLocate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.locateToCenter(mAMap);
            }
        });
        EventBusUtil.register(this);
    }

    @Override
    protected void initViewDataRes() {
        Bundle bundle=getIntent().getExtras();
        String routePath=bundle.getString("route");
        String polygonPath=bundle.getString("polygon");
        String startMarkerPointString=bundle.getString("origin");
        String endMarkerPointString=bundle.getString("destination");
        routeList=new ArrayList<LatLng>();
        if (routePath!=null&&!routePath.equals(""))
        {
            String[] routeStringList=routePath.split(";");
            for (String route :
                    routeStringList) {
                if (!route.equals(""))
                {
                    String[] latlngString=route.split(",");
                    double lat=Double.parseDouble(latlngString[0]);
                    double lng=Double.parseDouble(latlngString[1]);
                    LatLng routeLatLng = new LatLng(lng,lat);
                    routeList.add(routeLatLng);
                }

            }
        }

        polygonList=new ArrayList<LatLng>();
        if (polygonPath!=null&&!polygonPath.equals("")) {
            //polygonPath.substring()
            String[] polygonStringList = polygonPath.split(";");
            for (String polygon :
                    polygonStringList) {
                if (!polygon.equals("")) {
                    String[] latlngString = polygon.split(",");
                    if(latlngString.length>=2) {
                        double lat = Double.parseDouble(latlngString[0]);
                        double lng = Double.parseDouble(latlngString[1]);
                        LatLng polygonLatLng = new LatLng(lng, lat);
                        polygonList.add(polygonLatLng);
                    }
                    else{
                        Log.d("生成线路错误", "initViewDataRes: " );
                    }
                }

            }
        }
        if(startMarkerPointString!=null&&!startMarkerPointString.equals("")) {
            String[] startMarkerPointList = startMarkerPointString.split(",");
            double startLat = Double.parseDouble(startMarkerPointList[0]);
            double startLng = Double.parseDouble(startMarkerPointList[1]);
            startMarkerPoint = new LatLng(startLng, startLat);
        }
        if(endMarkerPointString!=null&&!endMarkerPointString.equals("")) {
            String[] endMarkerPointList = endMarkerPointString.split(",");
            double endLat = Double.parseDouble(endMarkerPointList[0]);
            double endLng = Double.parseDouble(endMarkerPointList[1]);
            endMarkerPoint = new LatLng(endLng, endLat);
        }

        initHeaderLayout(false);
        //setOptionItem("切换");
        setCenterTitle("任务地图");
        mMapView.onCreate(new Bundle());
        mAMap = mMapView.getMap();
        //mMapView.showZoomControls(false);//放大
        //mMapView.showScaleControl(true);//比例尺
        uiSettings=mAMap.getUiSettings();
        uiSettings.setScaleControlsEnabled(true);
        uiSettings.setZoomControlsEnabled(false);
        mPresenter.init();
        mAMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                return mPresenter.dealMarkerClick(marker);
            }
        });
        mAMap.setOnMapLoadedListener(mMapLoadedCallback);
        mAMap.addPolyline(new PolylineOptions().
                addAll(routeList).width(8).color(Color.argb(204, 0, 145, 234)));
        // 声明 多边形参数对象
        PolygonOptions polygonOptions = new PolygonOptions();
// 添加 多边形的每个顶点（顺序添加）
        for (LatLng latLng :
                polygonList) {
            polygonOptions.add(latLng);
        }

           // 多边形的填充色
        polygon=mAMap.addPolygon(polygonOptions.strokeWidth(6) // 多边形的边框
                .strokeColor(Color.argb(51,255,51,255)) // 边框颜色
                .fillColor(Color.argb(102, 23, 145, 252)));
        //定义Maker坐标点 104.0396410000,30.6799390000

        if (startMarkerPoint.latitude!=0)
        {
            //构建Marker图标

            View startMarkerView = LayoutInflater.from(getBaseContext()).inflate(R.layout.start_point_image,mMapView,false);
            BitmapDescriptor startBitmap = BitmapDescriptorFactory
                    .fromView(startMarkerView);
            View endMarkerView = LayoutInflater.from(getBaseContext()).inflate(R.layout.end_point_image,mMapView,false);
            BitmapDescriptor endBitmap = BitmapDescriptorFactory
                    .fromView(endMarkerView);
            //构建MarkerOption，用于在地图上添加Marker
            MarkerOptions startOption = new MarkerOptions()

                    .position(startMarkerPoint)
                    .icon(startBitmap);

            MarkerOptions endOption = new MarkerOptions()
                    .position(endMarkerPoint)
                    .icon(endBitmap);
            //在地图上添加Marker，并显示
            if (mAMap != null) {
                mAMap.addMarker(startOption);
                mAMap.addMarker(endOption);
            }
            //controlMapPointVisible();
        }
//        mIsAddStaEnd = true;
//        if (mIsMapLoadFinish) {
            //controlMapPointVisible();
//        }

    }

    private void SetCenterToStartAndEnd()
    {

    }

    /**
     * 地图加载完成回调方法。
     */
    private AMap.OnMapLoadedListener mMapLoadedCallback = new AMap.OnMapLoadedListener() {

        @Override
        public void onMapLoaded() {
//            mIsMapLoadFinish = true;
//            if (mIsAddStaEnd) {
//                controlMapPointVisible();
//            }

        }
    };



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.headerBackLayout:
                finish();
                break;
            case R.id.headerOptionLayout:
                break;
            default:
                super.onClick(v);
        }
    }

    protected void controlMapPointVisible() {
        if (startMarkerPoint.latitude!=0)
        {
            //是否包含线路 包含线路
            LatLngBounds bounds = new LatLngBounds.Builder()
                    .include(startMarkerPoint)
                    .include(endMarkerPoint)
                    .include(mPresenter.mStartLatLng)
                    .build();
            // 改变地图状态
            if (mAMap != null) {
                mAMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,0));
            }
        }
       else {
            if (mAMap != null) {
                mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mPresenter.mStartLatLng,17.0f));
            }
        }
    }

    public AMap getAMap() {
        return mAMap;
    }

    protected void refreshTip(AMapLocation location) {
        if (AMapLocation.LOCATION_TYPE_WIFI == location.getLocationType()) {
            if (View.GONE == mTipLayout.getVisibility()) {
                mTipLayout.setVisibility(View.VISIBLE);
            }
        } else if (AMapLocation.LOCATION_TYPE_GPS == location.getLocationType()) {
            if (View.VISIBLE == mTipLayout.getVisibility()) {
                mTipLayout.setVisibility(View.GONE);
            }
        }
        //mPositionDescribe.setText(location.getDescription());
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 80)
    public void receiveMissionOver(MissionOverResponse response) {
        if(response.getOrder()==MissionOverResponse.UPDATE_ROUTE) {

                if (polygon==null)
                {
                    return;
                }
                polygon.remove();
                polygonList=new ArrayList<LatLng>();
                if (response.getMessage()!=null&&!response.getMessage().equals("")) {
                    //polygonPath.substring()
                    String[] polygonStringList = response.getMessage().split(";");
                    for (String polygon :
                            polygonStringList) {
                        if (!polygon.equals("")) {
                            String[] latlngString = polygon.split(",");
                            if (latlngString.length>=2) {
                                double lat = Double.parseDouble(latlngString[0]);
                                double lng = Double.parseDouble(latlngString[1]);
                                LatLng polygonLatLng = new LatLng(lng, lat);
                                polygonList.add(polygonLatLng);
                            }
                            else{
                                Log.d("生成线路错误2", "initViewDataRes: " );
                            }
                        }

                    }
                }
// 声明 多边形参数对象
                PolygonOptions polygonOptions = new PolygonOptions();
// 添加 多边形的每个顶点（顺序添加）
                for (LatLng latLng :
                        polygonList) {
                    polygonOptions.add(latLng);
                }

                // 多边形的填充色
                polygon=mAMap.addPolygon(polygonOptions.strokeWidth(6) // 多边形的边框
                        .strokeColor(Color.argb(51,255,51,255)) // 边框颜色
                        .fillColor(Color.argb(102, 23, 145, 252)));

        }
    }

    protected void refreshLocateDescription(String title,String address) {
        if (View.VISIBLE != mPositionDescribe.getVisibility()) {
            return;
        }
        if(title.equals(""))
        {
            mPositionDescribe.setText("位置:"+address);
        }
        else{
            mPositionDescribe.setText("脚环:"+title+",位置:"+address);
        }
        //mPositionDescribe.setText(address);
    }

    protected void showCatchModeTipDialog(){
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    public void finish() {
        super.finish();
        EventBusUtil.unRegister(this);
        overridePendingTransition(R.anim.anim_no, R.anim.slide_bottom_out);
    }

    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        super.onDestroy();
    }
}
